﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StringSettingDescriptor.cs" company="Radical Research Ltd">
//   Copyright (c) Radical Research Ltd. The MIT License (MIT)
// </copyright>
// <summary>
//   
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace RadicalResearch.MiniState.Descriptors
{
    /// <summary>Manages String settings stored in a value collection.</summary>
    public class StringSettingDescriptor : SettingDescriptorBase
    {
        #region Constructors and Destructors

        /// <summary>Initializes a new instance of the <see cref="StringSettingDescriptor"/> class.</summary>
        /// <param name="valueKey">The valueKey used to identify the value in the value collection.</param>
        /// <param name="isValidated">if set to <c>true</c> value is validated with hash.</param>
        public StringSettingDescriptor(string valueKey, bool isValidated)
            : base(valueKey, isValidated)
        {
        }

        #endregion

        #region Public Methods

        /// <summary>Reads the value.</summary>
        /// <param name="values">The values.</param>
        /// <returns>value as an object</returns>
        public override object ReadValue(IValueCollection values)
        {
            return values[this.ValueKey];
        }

        /// <summary>
        /// Writes the value to the collection.
        /// </summary>
        /// <param name="values">The value collection to write to.</param>
        /// <param name="value">The value to write.</param>
        public override void WriteValue(IValueCollection values, object value)
        {
            // For nulls write an empty string.
            if (null == value)
            {
                values[this.ValueKey] = string.Empty;
                return;
            }

            if (!(value is string))
            {
                throw new SettingStoreException(string.Format("Value with key '{0}' is not a string", this.ValueKey));
            }

            values[this.ValueKey] = (string)value;
        }

        #endregion
    }
}